package cn.kgc.vue.shiro;

import cn.hutool.json.JSONUtil;
import cn.kgc.vue.commons.ResponseResult;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2023/12/5
 * @description
 */
@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {

    // 2 判定请求是否被允许    true   ->  controller
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.debug("---------------isAccessAllowed-----------------");
        try {
            executeLogin(request, response);
            return true;
        } catch (Exception e) {

            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                String result = JSONUtil.toJsonStr(ResponseResult.error().code(401).message("请求未认证,请认证后访问...."));
                writer.write(result);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }finally {
                writer.close();
            }

            return false;
        }

    }

    // 执行认证操作
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        log.debug("---------------executeLogin-----------------");
        // 获取toke
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new AuthenticationException("请认证后访问!!!");
        }

        // 验证token真伪
        Subject subject = getSubject(request, response);
        // string token  ->  AuthenticationToken
        JWTToken jwtToken = new JWTToken(token);

        subject.login(jwtToken);
        return true;
    }

    // 1 请求的预处理  OPTION   跨域
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        log.debug("---------------preHandle-----------------");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        // 跨域时会首先发送一个option请求，option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
